var express = require('express');
var router = express.Router();
const { Setting } = require('../../models');
const { delKey } = require('../../utils/redis');

router.get('/', async function(req, res, next) {
  try {
    const settings = await Setting.findOne()
    res.json({
      status: true,
      message: 'setting route',
      data: {
        settings,
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to fetch settings',
      error: [error.message]
    });
  }
});

router.put('/', async function(req, res, next) {
  try {
    const setting = await Setting.findOne();
    if (!setting) {
      return res.status(404).json({
        status: false,
        message: 'Setting not found',
      });
    }
    await setting.update(filterBody(req.body));
    // 删除 redis 缓存
    await delKey('setting');
    res.json({
      status: true,
      message: 'Setting update successfully',
      data: {
        setting
      }
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: 'Failed to update setting',
      error: [error.message]
    });
  }
})

function filterBody(body) {
  const { name, icp, copyright } = body;
  return {
    name: name ? name.trim() : '',
    icp: icp ? icp.trim() : '',
    copyright: copyright ? copyright.trim() : ''
  };
}

module.exports = router;
